package com.zut.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zut.dto.UserDto;
import com.zut.pojo.Employee;
import com.zut.pojo.R;
import com.zut.pojo.User;
import com.zut.service.UserService;
import com.zut.utils.SMSUtils;
import com.zut.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;


    /*
    *
    * 移动端用户登录时验证码获取
    * */

    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session){
        log.info("用户登录获取验证码的手机号为：{}",user.getPhone());
        String userPhone = user.getPhone();

        if (StringUtils.isNotEmpty(userPhone)){

            //生成验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("生成的验证码为：{}",code);

            //发送短信
            SMSUtils.sendMessage("瑞吉外卖","SMS_467485415",userPhone,code);

            //将验证码存到session
            session.setAttribute(userPhone,code);

            return R.success("获取验证码成功");

        }
        return R.error("手机号为空");

    }


    /*
     * 用户登录
     * */
    @PostMapping("/login")
    public R<User> login(HttpSession session, @RequestBody UserDto userDto){
        log.info("手机号：{}，验证码：{}",userDto.getPhone(), userDto.getCode());

        String phone = userDto.getPhone();

        String code = userDto.getCode();

        String trueCode = (String) session.getAttribute(phone);

        if (code.equals(trueCode) && trueCode != null){

            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone,phone);

            User user = userService.getOne(queryWrapper);

            if (user ==null){

                user = new User();
                user.setPhone(phone);

                userService.save(user);

            }

            session.setAttribute("user",user.getId());
            return R.success(user);

        }


        return R.error("登录失败");
    }


    /*
    * 用户退出
    * */

    @PostMapping("/loginout")
    public R<String> logout(HttpSession session){
        session.removeAttribute("user");

        return R.success("退出成功");
    }


}
